import 'dart:io';
import 'package:flutter/services.dart';
import 'package:mime/mime.dart';

void runAssetsServer() {
  _createServer(12345);
}

void _createServer(int port) async {
  try {
    HttpServer server = await HttpServer.bind(InternetAddress.anyIPv4, port);

    server.listen(_handle);
  } catch (e) {
    if (++port > 23456) {
      rethrow;
    } else {
      _createServer(++port);
    }
  }
}

void _handle(HttpRequest request) async {
  HttpResponse response = request.response;
  String path = 'assets' + request.requestedUri.path;
  List<int> body = [];

  try {
    body = (await rootBundle.load(path)).buffer.asUint8List();
  } catch (e) {
    response.statusCode = 404;
    response.close();
    return;
  }

  var contentType = ['text', 'html'];

  String? mimeType = lookupMimeType(path, headerBytes: body);

  if (mimeType != null) {
    contentType = mimeType.split('/');
  }

  response.headers.contentType =
      ContentType(contentType[0], contentType[1], charset: 'utf-8');
  response.add(body);
  response.close();
}
